package com.myself.springboot.springboot_study.controller;

import com.myself.springboot.springboot_study.dao.DepartmentDao;
import com.myself.springboot.springboot_study.dao.EmployeeDao;
import com.myself.springboot.springboot_study.entities.Department;
import com.myself.springboot.springboot_study.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;
@Controller
public class EmployController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String getAllEmploy(Model model) {
        Collection<Employee> all = employeeDao.getAll();
        model.addAttribute("emps",all);
        return "/emp/list";
    }

    @GetMapping("/emp")
    public String emp (Model model) {
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }
    @RequestMapping("/emp/add")
    public String addEmp (Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/emp/edit/{id}")
    public String EditEmp (@PathVariable Integer id,Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";

    }

    @RequestMapping("/emp/del/{id}")
    public String del(@PathVariable Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
